package cn.htsyb.synergy.utils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

/**
 * ResultSet封装工具
 * 
 * @author lakeside hubin_yuan.410@hotmail.com
 * @version V1.0.0
 * @since 1.0
 * @date 2022/5/11
 */
public class ResultSetUtil {

    public static Collection<HashMap<String, Object>> resultToListMap(ResultSet resultSet) throws Exception {
        ArrayList<HashMap<String, Object>> listMap = new ArrayList<HashMap<String, Object>>(resultSet.getRow());
        while (resultSet.next()) {
            listMap.add(metaToMap(resultSet));
        }
        return listMap;
    }

    private static HashMap<String, Object> metaToMap(ResultSet entryRS) throws Exception {
        ResultSetMetaData metaDataRS = entryRS.getMetaData();
        HashMap<String, Object> metaMap = new HashMap<String, Object>();
        for (int i = 1; i <= metaDataRS.getColumnCount(); i++) {
            String name = metaDataRS.getColumnLabel(i).trim();
            Object value = entryRS.getObject(name);
            metaMap.put(name, value);
        }
        return metaMap;
    }

    public static <T> ArrayList<T> resultToListBean(ResultSet resultSet, Class<T> clazz) throws Exception {
        ArrayList<T> listT = new ArrayList<T>(resultSet.getRow());
        while (resultSet.next()) {
            listT.add(metaToBean(resultSet, clazz));
        }
        return listT;
    }

    private static <T> T metaToBean(ResultSet entryRS, Class<T> clazz) throws Exception {
        T entry = clazz.getDeclaredConstructor().newInstance();
        ResultSetMetaData metaDataRS = entryRS.getMetaData();
        for (int i = 1; i <= metaDataRS.getColumnCount(); i++) {
            String name = metaDataRS.getColumnLabel(i).trim();
            PropertyDescriptor prop = null;
            try {
                prop = new PropertyDescriptor(name, entry.getClass());
            } catch (IntrospectionException e) {
                e.printStackTrace();
            }
            if (prop != null && prop.getWriteMethod() != null) {
                prop.getWriteMethod().invoke(entry, entryRS.getObject(name));
            }
        }
        return entry;
    }
}
